import { createFileRoute } from '@tanstack/react-router'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { 
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { 
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { 
  Search,
  Edit,
  Package,
  Clock,
  CheckCircle,
  DollarSign,
  Truck,
  Upload,
  X,
  Save,
  MoreHorizontal,
  Trash2,
  RefreshCw
} from 'lucide-react'
import { useState, useEffect } from 'react'
import { toast } from 'sonner'

export const Route = createFileRoute('/seals/orders')({
  component: OrdersPage,
})

// API数据类型定义
interface OrderUser {
  id: number;
  phone: string;
}

interface OrderItem {
  id: number;
  userId: number;
  orderNo: string;
  status: number;
  totalPrice: number;
  discountAmount: number;
  sealType: number;
  sealMaterialId: number;
  sealClassifyIds: string;
  reasons: string;
  province: string;
  city: string;
  district: string;
  provinceCode: number;
  cityCode: number;
  districtCode: number;
  phone: string;
  bossPhone: string;
  licenseName: string;
  remark: string;
  addressId: number;
  uploadFileStatus: number;
  courierCompany: number;
  courierNo: string;
  isRefund: number;
  isDeleted: number;
  createdAt: number;
  updatedAt: number;
  beian: string;
  statusText: string;
  sealTypeText: string;
  sealMaterialText: string;
  sealClassifyArr: string[];
  createdAtFormat: string;
  uploadFileStatusText: string;
  user: OrderUser;
}

// API响应数据类型
interface OrderListApiResponse {
  code: number;
  msg: string;
  data: {
    list: OrderItem[];
    total: number;
    pageNum: string;
    pageSize: string;
    totalPages: number;
  };
}

// 订单状态枚举
const STATUS_WAIT_PAY = 0;
const STATUS_PENDING = 1;
const STATUS_PROCESSING = 2;
const STATUS_SUBMIT = 3;
const STATUS_SHIPPED = 4;
const STATUS_AFTER = 5;
const STATUS_FINISH = 6;

// 快递公司枚举
const COURIER_COMPANIES = {
  1: '顺丰速运',
  2: 'EMS',
  3: '韵达快递',
  4: '中通快递',
  5: '圆通速递',
  6: '申通快递',
  7: '京东物流',
  8: '其他',
};

// 操作类型
interface OrderOperation {
  id: number;
  price?: number;
  status?: number;
  courierCompany?: number;
  courierNo?: string;
  beian?: File;
  close?: boolean;
  delete?: boolean;
}

// 订单看板数据类型
interface DashboardItem {
  text: string;
  status: number;
  value: number;
}

interface DashboardResponse {
  code: number;
  msg: string;
  data: DashboardItem[];
}


// API调用函数
const fetchOrders = async (params: {
  pageNum: number;
  pageSize: number;
  orderNo?: string;
  status?: number | null;
  phone?: string;
}): Promise<ApiResponse> => {
  const searchParams = new URLSearchParams({
    pageNum: params.pageNum.toString(),
    pageSize: params.pageSize.toString(),
  });

  // 只有当参数有值时才添加到URL中
  if (params.orderNo && params.orderNo.trim()) {
    searchParams.append('orderNo', params.orderNo);
  }
  
  if (params.status !== null && params.status !== undefined) {
    searchParams.append('status', params.status.toString());
  }
  
  if (params.phone && params.phone.trim()) {
    searchParams.append('phone', params.phone);
  }

  // 获取存储的token
  const token = localStorage.getItem('auth_token');
  
  if (!token) {
    throw new Error('未找到认证token，请重新登录');
  }

  const response = await fetch(`/huibanhao/seal/orderList?${searchParams}`, {
    headers: {
      'Authorization': token,
      'Accept': 'application/json',
    },
  });

  if (!response.ok) {
    if (response.status === 401) {
      throw new Error('认证失败，请重新登录');
    }
    throw new Error(`请求失败: ${response.status}`);
  }

  return response.json();
};

// 订单看板API函数
const fetchOrderDashboard = async (): Promise<DashboardResponse> => {
  const token = localStorage.getItem('auth_token');
  
  if (!token) {
    throw new Error('未找到认证token，请重新登录');
  }

  const response = await fetch('/huibanhao/seal/orderDashboard', {
    headers: {
      'Authorization': token,
      'Accept': 'application/json',
    },
  });

  if (!response.ok) {
    if (response.status === 401) {
      throw new Error('认证失败，请重新登录');
    }
    throw new Error(`请求失败: ${response.status}`);
  }

  return response.json();
};

// 订单操作API函数
const operateOrder = async (operation: OrderOperation): Promise<{code: number, msg: string}> => {
  const token = localStorage.getItem('auth_token');
  
  if (!token) {
    throw new Error('未找到认证token，请重新登录');
  }

  // 如果有文件上传，使用FormData
  let body: FormData | string;
  let headers: Record<string, string> = {
    'Authorization': token,
  };

  if (operation.beian) {
    const formData = new FormData();
    formData.append('id', operation.id.toString());
    if (operation.price !== undefined) formData.append('price', (operation.price * 100).toString());
    if (operation.status !== undefined) formData.append('status', operation.status.toString());
    if (operation.courierCompany !== undefined) formData.append('courierCompany', operation.courierCompany.toString());
    if (operation.courierNo) formData.append('courierNo', operation.courierNo);
    if (operation.close !== undefined) formData.append('close', operation.close.toString());
    if (operation.delete !== undefined) formData.append('delete', operation.delete.toString());
    formData.append('beian', operation.beian);
    body = formData;
  } else {
    headers['Content-Type'] = 'application/json';
    const data: any = { id: operation.id };
    if (operation.price !== undefined) data.price = operation.price * 100; // 转换为分
    if (operation.status !== undefined) data.status = operation.status;
    if (operation.courierCompany !== undefined) data.courierCompany = operation.courierCompany;
    if (operation.courierNo) data.courierNo = operation.courierNo;
    if (operation.close !== undefined) data.close = operation.close;
    if (operation.delete !== undefined) data.delete = operation.delete;
    body = JSON.stringify(data);
  }

  const response = await fetch('/huibanhao/seal/operate', {
    method: 'POST',
    headers,
    body,
  });

  if (!response.ok) {
    if (response.status === 401) {
      throw new Error('认证失败，请重新登录');
    }
    throw new Error(`操作失败: ${response.status}`);
  }

  return response.json();
};

// 退款API函数
const refundOrder = async (id: number): Promise<{code: number; msg: string}> => {
  const token = localStorage.getItem('auth_token');
  
  if (!token) {
    throw new Error('未找到认证token，请重新登录');
  }

  const response = await fetch('/huibanhao/seal/refund', {
    method: 'POST',
    headers: {
      'Authorization': token,
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ id }),
  });

  if (!response.ok) {
    if (response.status === 401) {
      throw new Error('认证失败，请重新登录');
    }
    throw new Error(`请求失败: ${response.status}`);
  }

  return response.json();
};

// 获取订单详情API
const fetchOrderDetail = async (orderId: number): Promise<OrderDetailApiResponse> => {
  const token = localStorage.getItem('auth_token');

  if (!token) {
    throw new Error('未找到认证token，请重新登录');
  }

  const response = await fetch(`/huibanhao/seal/order/${orderId}`, {
    headers: {
      'Authorization': token,
      'Accept': 'application/json',
    },
  });

  if (!response.ok) {
    if (response.status === 401) {
      throw new Error('认证失败，请重新登录');
    }
    throw new Error(`请求失败: ${response.status}`);
  }

  return response.json();
};

// 更新订单操作API
const updateOrderOperation = async (operation: OrderOperation): Promise<{code: number; msg: string}> => {
  const token = localStorage.getItem('auth_token');
  
  if (!token) {
    throw new Error('未找到认证token，请重新登录');
  }

  // 如果有文件上传，使用FormData
  let body: FormData | string;
  let headers: Record<string, string> = {
    'Authorization': token,
  };

  if (operation.beian) {
    const formData = new FormData();
    formData.append('id', operation.id.toString());
    if (operation.price !== undefined) formData.append('price', (operation.price * 100).toString());
    if (operation.status !== undefined) formData.append('status', operation.status.toString());
    if (operation.courierCompany !== undefined) formData.append('courierCompany', operation.courierCompany.toString());
    if (operation.courierNo) formData.append('courierNo', operation.courierNo);
    if (operation.close !== undefined) formData.append('close', operation.close.toString());
    if (operation.delete !== undefined) formData.append('delete', operation.delete.toString());
    formData.append('beian', operation.beian);
    body = formData;
  } else {
    headers['Content-Type'] = 'application/json';
    const data: any = { id: operation.id };
    if (operation.price !== undefined) data.price = operation.price * 100; // 转换为分
    if (operation.status !== undefined) data.status = operation.status;
    if (operation.courierCompany !== undefined) data.courierCompany = operation.courierCompany;
    if (operation.courierNo) data.courierNo = operation.courierNo;
    if (operation.close !== undefined) data.close = operation.close;
    if (operation.delete !== undefined) data.delete = operation.delete;
    body = JSON.stringify(data);
  }

  const response = await fetch('/huibanhao/seal/operate', {
    method: 'POST',
    headers,
    body,
  });

  if (!response.ok) {
    if (response.status === 401) {
      throw new Error('认证失败，请重新登录');
    }
    throw new Error(`操作失败: ${response.status}`);
  }

  return response.json();
};

function OrdersPage() {
  const [orderIdSearch, setOrderIdSearch] = useState('')
  const [phoneSearch, setPhoneSearch] = useState('')
  const [orders, setOrders] = useState<OrderItem[]>([])
  const [loading, setLoading] = useState(false)
  const [pagination, setPagination] = useState({ pageNum: 1, pageSize: 10, total: 0, totalPages: 1 })
  const [statusFilter, setStatusFilter] = useState<number | null>(null)
  const [dashboardData, setDashboardData] = useState<DashboardItem[]>([])
  const [dashboardLoading, setDashboardLoading] = useState(false)

  // 操作对话框状态
  const [operationDialog, setOperationDialog] = useState<{ open: boolean; order: OrderItem | null; type: string | null }>({ open: false, order: null, type: null })
  const [operationForm, setOperationForm] = useState({ price: '', status: '', courierCompany: '', courierNo: '', beianFile: null as File | null })
  const [operationLoading, setOperationLoading] = useState(false)

  // 退款对话框状态
  const [refundDialog, setRefundDialog] = useState<{ open: boolean; order: OrderItem | null }>({ open: false, order: null })
  const [refundReason, setRefundReason] = useState('')
  const [refundLoading, setRefundLoading] = useState<{[key: number]: boolean}>({})

    // 订单详情对话框状态
    const [isDetailDialogOpen, setIsDetailDialogOpen] = useState(false);
    const [selectedOrderDetail, setSelectedOrderDetail] = useState<OrderDetail | null>(null);
    const [isDetailLoading, setIsDetailLoading] = useState(false);
    const [imagePreview, setImagePreview] = useState<{ open: boolean; url: string | null }>({ open: false, url: null });

    // 获取徽章样式
    const getStatusBadgeStyle = (status: number) => {
      switch (status) {
        case STATUS_WAIT_PAY:
          return { backgroundColor: '#FFEDD5', color: '#F97316' }; // 橙色
        case STATUS_PENDING:
          return { backgroundColor: '#DBEAFE', color: '#3B82F6' }; // 蓝色
        case STATUS_PROCESSING:
          return { backgroundColor: '#FEF08A', color: '#CA8A04' }; // 黄色
        case STATUS_SUBMIT:
          return { backgroundColor: '#E0E7FF', color: '#4F46E5' }; // 靛蓝色
        case STATUS_SHIPPED:
          return { backgroundColor: '#EDE9FE', color: '#6D28D9' }; // 紫色
        case STATUS_AFTER:
          return { backgroundColor: '#FEE2E2', color: '#EF4444' }; // 红色
        case STATUS_FINISH:
          return { backgroundColor: '#D1FAE5', color: '#059669' }; // 绿色
        default:
          return { backgroundColor: '#F3F4F6', color: '#4B5563' };
      }
    };

    // 查看详情
    const handleViewDetails = async (orderId: number) => {
      setIsDetailDialogOpen(true);
      setIsDetailLoading(true);
      try {
        const result = await fetchOrderDetail(orderId);
        if (result.code === 200) {
          setSelectedOrderDetail(result.data);
        } else {
          toast.error(result.msg || '获取订单详情失败');
          setIsDetailDialogOpen(false); // 获取失败时关闭对话框
        }
      } catch (error: any) {
        toast.error(error.message || '获取订单详情时发生错误');
        setIsDetailDialogOpen(false); // 发生错误时关闭对话框
      } finally {
        setIsDetailLoading(false);
      }
    };

    // 加载订单列表
    const loadOrders = async () => {
      setLoading(true);
      try {
        const response = await fetchOrders({
          pageNum: pagination.pageNum,
          pageSize: pagination.pageSize,
          orderNo: orderIdSearch || undefined,
          status: statusFilter,
          phone: phoneSearch || undefined,
        });

        if (response.code === 200) {
          setOrders(response.data.list);
          setPagination(prev => ({
            ...prev,
            total: response.data.total,
            totalPages: response.data.totalPages,
          }));
        } else {
          toast.error(response.msg || '获取订单数据失败');
          setOrders([]);
        }
      } catch (error) {
        console.error('Failed to load orders:', error);
        const errorMessage = error instanceof Error ? error.message : '获取订单数据失败';
        toast.error(errorMessage);
        setOrders([]);
      } finally {
        setLoading(false);
      }
    };

  // 加载看板数据
  const loadDashboard = async () => {
    setDashboardLoading(true);
    try {
      const response = await fetchOrderDashboard();
      if (response.code === 200) {
        setDashboardData(response.data);
      } else {
        console.error('获取看板数据失败:', response.msg);
      }
    } catch (error) {
      console.error('Failed to load dashboard:', error);
    } finally {
      setDashboardLoading(false);
    }
  };

  // 页面加载时获取数据
  useEffect(() => {
    loadOrders();
  }, [pagination.pageNum, pagination.pageSize, statusFilter]);

  // 初次加载看板数据
  useEffect(() => {
    loadDashboard();
  }, []);

  // 手动搜索函数
  const handleSearch = () => {
    setPagination(prev => ({ ...prev, pageNum: 1 }));
    loadOrders();
  };

  // 处理回车搜索
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  // 由于现在通过API过滤，不需要前端过滤
  const filteredOrders = orders;

  // 获取状态对应的样式和图标
  const getStatusCardStyle = (status: number) => {
    switch (status) {
      case STATUS_WAIT_PAY:
        return {
          textColor: 'text-gray-600',
          iconColor: 'text-gray-600',
          icon: Clock,
          ringColor: 'ring-gray-500'
        };
      case STATUS_PENDING:
        return {
          textColor: 'text-blue-600',
          iconColor: 'text-blue-600',
          icon: Clock,
          ringColor: 'ring-blue-500'
        };
      case STATUS_PROCESSING:
        return {
          textColor: 'text-orange-600',
          iconColor: 'text-orange-600',
          icon: Package,
          ringColor: 'ring-orange-500'
        };
      case STATUS_SUBMIT:
        return {
          textColor: 'text-purple-600',
          iconColor: 'text-purple-600',
          icon: Upload,
          ringColor: 'ring-purple-500'
        };
      case STATUS_SHIPPED:
        return {
          textColor: 'text-indigo-600',
          iconColor: 'text-indigo-600',
          icon: Truck,
          ringColor: 'ring-indigo-500'
        };
      case STATUS_AFTER:
        return {
          textColor: 'text-red-600',
          iconColor: 'text-red-600',
          icon: X,
          ringColor: 'ring-red-500'
        };
      case STATUS_FINISH:
        return {
          textColor: 'text-green-600',
          iconColor: 'text-green-600',
          icon: CheckCircle,
          ringColor: 'ring-green-500'
        };
      case 99: // 待退款
        return {
          textColor: 'text-yellow-600',
          iconColor: 'text-yellow-600',
          icon: DollarSign,
          ringColor: 'ring-yellow-500'
        };
      default:
        return {
          textColor: 'text-gray-600',
          iconColor: 'text-gray-600',
          icon: Clock,
          ringColor: 'ring-gray-500'
        };
    }
  };

  // 打开操作对话框
  const openOperationDialog = (order: OrderItem, type: 'price' | 'status' | 'courier' | 'beian' | 'close' | 'delete') => {
    setOperationDialog({ open: true, order, type });
    // 重置表单
    setOperationForm({
      price: (order.totalPrice / 100).toString(),
      status: order.status.toString(),
      courierCompany: order.courierCompany?.toString() || '',
      courierNo: order.courierNo || '',
      beianFile: null,
    });
  };

  // 关闭操作对话框
  const closeOperationDialog = () => {
    setOperationDialog({ open: false, order: null, type: '' });
    setOperationForm({
      price: '',
      status: '',
      courierCompany: '',
      courierNo: '',
      beianFile: null,
    });
  };

  // 执行操作
  const handleOperation = async () => {
    if (!operationDialog.order) return;

    setOperationLoading(true);
    try {
      const operation: OrderOperation = {
        id: operationDialog.order.id,
      };

      switch (operationDialog.type) {
        case 'price':
          operation.price = parseFloat(operationForm.price);
          break;
        case 'status':
          operation.status = parseInt(operationForm.status);
          break;
        case 'courier':
          operation.courierCompany = parseInt(operationForm.courierCompany);
          operation.courierNo = operationForm.courierNo;
          break;
        case 'beian':
          operation.beian = operationForm.beianFile || undefined;
          break;
        case 'close':
          operation.close = true;
          break;
        case 'delete':
          operation.delete = true;
          break;
      }

      const result = await operateOrder(operation);
      
      if (result.code === 200) {
        // 对于删除和关闭操作，立即关闭对话框并乐观更新
        if (operationDialog.type === 'delete' || operationDialog.type === 'close') {
          // 乐观更新：从本地状态中移除订单（删除和关闭都会从列表中移除）
          setOrders(prev => prev.filter(order => order.id !== operationDialog.order?.id));
          
          // 立即关闭对话框
          closeOperationDialog();
          
          // 在后台并行刷新数据
          Promise.all([loadOrders(), loadDashboard()]).catch(error => {
            console.error('Background refresh failed:', error);
          });
          
          // 显示成功提示
          if (operationDialog.type === 'delete') {
            toast.success('订单删除成功');
          } else if (operationDialog.type === 'close') {
            toast.success('订单关闭成功');
          }
        } else {
          // 其他操作仍然等待数据刷新完成
          await Promise.all([loadOrders(), loadDashboard()]);
          closeOperationDialog();
          
          // 显示成功提示
          if (operationDialog.type === 'price') {
            toast.success('订单金额修改成功');
          } else if (operationDialog.type === 'status') {
            toast.success('订单状态修改成功');
          } else if (operationDialog.type === 'courier') {
            toast.success('物流信息更新成功');
          } else if (operationDialog.type === 'beian') {
            toast.success('备案回执上传成功');
          }
        }
      } else {
        toast.error(result.msg || '操作失败');
      }
    } catch (error) {
      console.error('Operation failed:', error);
      const errorMessage = error instanceof Error ? error.message : '操作失败';
      toast.error(errorMessage);
    } finally {
      setOperationLoading(false);
    }
  };

  // 打开退款确认对话框
  const openRefundDialog = (order: OrderItem) => {
    setRefundDialog({
      open: true,
      order: order,
    });
  };

  // 关闭退款确认对话框
  const closeRefundDialog = () => {
    setRefundDialog({
      open: false,
      order: null,
    });
  };

  // 处理退款确认
  const handleRefundConfirm = async () => {
    if (!refundDialog.order) return;
    
    const orderId = refundDialog.order.id;
    setRefundLoading(prev => ({ ...prev, [orderId]: true }));
    
    try {
      const result = await refundOrder(orderId);
      if (result.code === 200) {
        // 退款成功，关闭对话框并刷新数据
        closeRefundDialog();
        await Promise.all([loadOrders(), loadDashboard()]);
        toast.success('退款申请提交成功');
      } else {
        toast.error(result.msg || '退款失败');
      }
    } catch (error) {
      console.error('Refund failed:', error);
      const errorMessage = error instanceof Error ? error.message : '退款失败';
      toast.error(errorMessage);
    } finally {
      setRefundLoading(prev => ({ ...prev, [orderId]: false }));
    }
  };

  const getStatusBadge = (status: number, statusText: string) => {
    switch (status) {
      case STATUS_WAIT_PAY:
        return <Badge className="bg-gray-100 text-gray-800">{statusText}</Badge>
      case STATUS_PENDING:
        return <Badge className="bg-yellow-100 text-yellow-800">{statusText}</Badge>
      case STATUS_PROCESSING:
        return <Badge className="bg-blue-100 text-blue-800">{statusText}</Badge>
      case STATUS_SUBMIT:
        return <Badge className="bg-purple-100 text-purple-800">{statusText}</Badge>
      case STATUS_SHIPPED:
        return <Badge className="bg-orange-100 text-orange-800">{statusText}</Badge>
      case STATUS_AFTER:
        return <Badge className="bg-red-100 text-red-800">{statusText}</Badge>
      case STATUS_FINISH:
        return <Badge className="bg-green-100 text-green-800">{statusText}</Badge>
      default:
        return <Badge variant="outline">{statusText}</Badge>
    }
  }

  // 获取上传状态徽章（带彩色圆点）
  const getUploadStatusBadge = (uploadFileStatus: number, uploadFileStatusText: string) => {
    // 根据上传状态数值判断颜色
    // 假设：0=待完善(橙色)，1=已完成(绿色)，其他状态可根据实际情况调整
    switch (uploadFileStatus) {
      case 0: // 待完善
        return (
          <Badge variant="outline" className="text-orange-600 border-orange-200">
            <div className="w-2 h-2 rounded-full bg-orange-500 mr-1.5"></div>
            {uploadFileStatusText}
          </Badge>
        )
      case 1: // 已完成
        return (
          <Badge variant="outline" className="text-green-600 border-green-200">
            <div className="w-2 h-2 rounded-full bg-green-500 mr-1.5"></div>
            {uploadFileStatusText}
          </Badge>
        )
      default:
        return (
          <Badge variant="outline">
            <div className="w-2 h-2 rounded-full bg-gray-400 mr-1.5"></div>
            {uploadFileStatusText}
          </Badge>
        )
    }
  }

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div>
        <h3 className="text-2xl font-bold text-gray-900 dark:text-white">在线刻章-订单管理</h3>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
        {dashboardLoading ? (
          // 加载状态
          Array.from({ length: 5 }).map((_, index) => (
            <Card key={index} className="animate-pulse">
              <CardContent className="p-4">
                <div className="flex items-center">
                  <div className="h-6 w-8 bg-gray-200 rounded"></div>
                  <div className="ml-auto h-4 w-4 bg-gray-200 rounded"></div>
                </div>
                <div className="h-3 w-12 bg-gray-200 rounded mt-1"></div>
              </CardContent>
            </Card>
          ))
        ) : (
          // 实际数据
          dashboardData.map((item) => {
            const style = getStatusCardStyle(item.status);
            const IconComponent = style.icon;
            const isSelected = statusFilter === item.status;
            
            return (
              <Card 
                key={item.status}
                className={`cursor-pointer transition-all hover:shadow-md ${isSelected ? `ring-2 ${style.ringColor}` : ''}`}
                onClick={() => {
                  const newStatus = statusFilter === item.status ? null : item.status;
                  setStatusFilter(newStatus);
                  setPagination(prev => ({ ...prev, pageNum: 1 }));
                }}
              >
                <CardContent className="p-4">
                  <div className="flex items-center">
                    <div className={`text-xl font-bold ${style.textColor}`}>
                      {item.value}
                    </div>
                    <div className={`ml-auto ${style.iconColor}`}>
                      <IconComponent className="h-4 w-4" />
                    </div>
                  </div>
                  <p className="text-xs text-muted-foreground mt-1">{item.text}</p>
                </CardContent>
              </Card>
            );
          })
        )}
      </div>

      {/* 订单列表 */}
      <Card>
        <CardContent>
          
          {/* 搜索框 */}
          <div className="flex items-center space-x-2 mb-4 pt-4">
            <div className="relative">
              <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
              <Input
                placeholder="搜索订单号..."
                value={orderIdSearch}
                onChange={(e) => setOrderIdSearch(e.target.value)}
                onKeyPress={handleKeyPress}
                className="pl-10 w-64"
              />
            </div>
            <div className="relative">
              <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
              <Input
                placeholder="搜索手机号..."
                value={phoneSearch}
                onChange={(e) => setPhoneSearch(e.target.value)}
                onKeyPress={handleKeyPress}
                className="pl-10 w-48"
              />
            </div>
            <Button 
              variant="default" 
              onClick={handleSearch}
              disabled={loading}
            >
              <Search className="mr-2 h-4 w-4" />
              搜索
            </Button>
            <Button 
              variant="outline" 
              onClick={() => {
                setStatusFilter(null);
                setOrderIdSearch('');
                setPhoneSearch('');
                // 重置后自动搜索
                setTimeout(() => {
                  setPagination(prev => ({ ...prev, pageNum: 1 }));
                  loadOrders();
                }, 0);
              }}
              disabled={!statusFilter && !orderIdSearch && !phoneSearch}
            >
              重置
            </Button>
          </div>

          {/* 订单表格 */}
          <div className="border rounded-lg">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>订单号</TableHead>
                  <TableHead>订单状态</TableHead>
                  <TableHead>印章类型</TableHead>
                  <TableHead>印章材质</TableHead>
                  <TableHead>印章分类</TableHead>
                  <TableHead>下单人手机号</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead>订单价格</TableHead>
                  <TableHead>材料上传状态</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={10} className="text-center py-8">
                      <div className="flex items-center justify-center">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                        <span className="ml-2">加载中...</span>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : filteredOrders.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={10} className="text-center py-8 text-gray-500">
                      暂无数据
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredOrders.map((order) => (
                    <TableRow key={order.id}>
                      <TableCell>
                        <span 
                          className="text-blue-600 hover:underline cursor-pointer"
                          onClick={() => handleViewDetails(order.id)} // 添加点击事件
                        >
                          {order.orderNo}
                        </span>
                        {order.isRefund === 1 && (
                          <Button 
                            variant="outline"
                            size="sm"
                            className="ml-2 h-6 px-2 text-xs text-red-600 border-red-600 hover:bg-red-50 hover:text-red-700"
                            onClick={() => openRefundDialog(order)}
                          >
                            退款
                          </Button>
                        )}
                      </TableCell>
                      <TableCell>
                        <Badge style={getStatusBadgeStyle(order.status)}>{order.statusText}</Badge>
                      </TableCell>
                      
                      {/* 印章类型 */}
                      <TableCell>
                        <div className="font-medium">
                          {order.sealTypeText}
                        </div>
                      </TableCell>
                      
                      {/* 印章材质 */}
                      <TableCell>
                        <div className="text-sm">
                          {order.sealMaterialText}
                        </div>
                      </TableCell>
                      
                      {/* 印章分类 */}
                      <TableCell>
                        <div className="space-y-1">
                          {order.sealClassifyArr.map((classify, index) => (
                            <div key={index} className="text-sm">
                              {classify.length > 10 ? `${classify.substring(0, 10)}...` : classify}
                            </div>
                          ))}
                        </div>
                      </TableCell>
                      
                      {/* 手机号 */}
                      <TableCell>
                        <div className="font-medium">
                          {order.user.phone}
                        </div>
                      </TableCell>
                      
                      {/* 创建时间 */}
                      <TableCell className="text-sm text-gray-500">
                        {order.createdAtFormat}
                      </TableCell>
                      
                      {/* 总价格 */}
                      <TableCell>
                        <div className="font-medium text-green-600">
                          ¥{(order.totalPrice / 100).toFixed(2)}
                        </div>
                      </TableCell>
                      
                      {/* 材料上传状态 */}
                      <TableCell>
                        {getUploadStatusBadge(order.uploadFileStatus, order.uploadFileStatusText)}
                      </TableCell>
                      
                      {/* 操作 */}
                      <TableCell className="text-right">
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                              <span className="sr-only">打开菜单</span>
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end" className="w-48">
                            <DropdownMenuLabel>订单操作</DropdownMenuLabel>
                            <DropdownMenuSeparator />
                            
                            {/* 修改金额 - 仅在待付款状态下可用 */}
                            {order.status === STATUS_WAIT_PAY && (
                              <DropdownMenuItem 
                                onClick={() => openOperationDialog(order, 'price')}
                                className="cursor-pointer"
                              >
                                <DollarSign className="mr-2 h-4 w-4" />
                                修改金额
                              </DropdownMenuItem>
                            )}
                            
                            {/* 修改状态 - 仅在特定状态下可修改 */}
                            {(order.status === STATUS_PENDING || order.status === STATUS_PROCESSING) && (
                              <DropdownMenuItem 
                                onClick={() => openOperationDialog(order, 'status')}
                                className="cursor-pointer"
                              >
                                <Edit className="mr-2 h-4 w-4" />
                                修改状态
                              </DropdownMenuItem>
                            )}
                            
                            {/* 添加物流信息 - 仅在提交备案状态下可用 */}
                            {order.status === STATUS_SUBMIT && (
                              <DropdownMenuItem 
                                onClick={() => openOperationDialog(order, 'courier')}
                                className="cursor-pointer"
                              >
                                <Truck className="mr-2 h-4 w-4" />
                                {order.courierNo ? '修改物流信息' : '添加物流信息'}
                              </DropdownMenuItem>
                            )}
                            
                            {/* 上传备案回执 - 在提交备案和已发货状态下可用 */}
                            {(order.status === STATUS_SUBMIT || order.status === STATUS_SHIPPED) && (
                              <DropdownMenuItem 
                                onClick={() => openOperationDialog(order, 'beian')}
                                className="cursor-pointer"
                              >
                                <Upload className="mr-2 h-4 w-4" />
                                {order.beian ? '更新备案回执' : '上传备案回执'}
                              </DropdownMenuItem>
                            )}
                            
                            {/* 分隔线 - 在有操作项时显示 */}
                            {(order.status === STATUS_WAIT_PAY || 
                              order.status === STATUS_PENDING || 
                              order.status === STATUS_PROCESSING || 
                              order.status === STATUS_SUBMIT || 
                              order.status === STATUS_SHIPPED) && (
                              <DropdownMenuSeparator />
                            )}
                            
                            {/* 关闭订单 - 所有状态都可以关闭 */}
                            <DropdownMenuItem 
                              onClick={() => openOperationDialog(order, 'close')}
                              className="cursor-pointer text-red-600 focus:text-red-600 focus:bg-red-50"
                            >
                              <X className="mr-2 h-4 w-4" />
                              关闭订单
                            </DropdownMenuItem>
                            
                            {/* 删除订单 - 最危险的操作 */}
                            <DropdownMenuItem 
                              onClick={() => openOperationDialog(order, 'delete')}
                              className="cursor-pointer text-red-700 focus:text-red-700 focus:bg-red-100"
                            >
                              <Trash2 className="mr-2 h-4 w-4" />
                              删除订单
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>

          {/* 分页信息 */}
          <div className="flex items-center justify-between mt-4">
            <div className="text-sm text-gray-500">
              显示第 {pagination.pageNum} 页，共 {pagination.totalPages} 页，总计 {pagination.total} 个订单
            </div>
            <div className="flex items-center space-x-2">
              <Button 
                variant="outline" 
                size="sm" 
                disabled={pagination.pageNum <= 1 || loading}
                onClick={() => setPagination(prev => ({ ...prev, pageNum: prev.pageNum - 1 }))}
              >
                上一页
              </Button>
              <span className="text-sm text-gray-500">
                {pagination.pageNum} / {pagination.totalPages}
              </span>
              <Button 
                variant="outline" 
                size="sm" 
                disabled={pagination.pageNum >= pagination.totalPages || loading}
                onClick={() => setPagination(prev => ({ ...prev, pageNum: prev.pageNum + 1 }))}
              >
                下一页
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 订单详情对话框 */}
      {isDetailDialogOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-3xl max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold">订单详情</h3>
              <Button variant="ghost" size="sm" onClick={() => setIsDetailDialogOpen(false)}>
                <X className="h-4 w-4" />
              </Button>
            </div>
            {isDetailLoading ? (
              <div className="flex items-center justify-center py-12">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                <span className="ml-2">加载中...</span>
              </div>
            ) : selectedOrderDetail ? (
              <div className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                  <div className="col-span-1 space-y-2">
                    <p><strong>订单号:</strong> {selectedOrderDetail.orderNo}</p>
                    <p><strong>订单状态:</strong> {selectedOrderDetail.statusText}</p>
                    <p><strong>下单人手机号:</strong> {selectedOrderDetail.phone}</p>
                    <p><strong>法人手机号:</strong> {selectedOrderDetail.bossPhone}</p>
                  </div>
                  <div className="col-span-1 space-y-2">
                    <p><strong>总价:</strong> ¥{(selectedOrderDetail.totalPrice / 100).toFixed(2)}</p>
                    <p><strong>折扣:</strong> ¥{(selectedOrderDetail.discountAmount / 100).toFixed(2)}</p>
                    <p><strong>实付:</strong> ¥{(selectedOrderDetail.payPrice / 100).toFixed(2)}</p>
                    <p><strong>快递单号:</strong> {selectedOrderDetail.courierNo || '暂无'}</p>
                  </div>
                </div>
                <div className="border-t pt-4">
                  <h4 className="font-semibold mb-2">刻章信息</h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                    <p><strong>印章类型:</strong> {selectedOrderDetail.sealType}</p>
                    <p><strong>印章材质:</strong> {selectedOrderDetail.sealMaterialId}</p>
                    <p><strong>印章分类:</strong> {selectedOrderDetail.sealClassifyArr.join(', ')}</p>
                    <p><strong>刻章事由:</strong> {selectedOrderDetail.reasons.join(', ')}</p>
                    <p><strong>备案省市区:</strong> {selectedOrderDetail.province} {selectedOrderDetail.city} {selectedOrderDetail.district}</p>
                    <p><strong>公司名称:</strong> {selectedOrderDetail.licenseName || '未提供'}</p>
                  </div>
                </div>
                {selectedOrderDetail.addressDetail && (
                  <div className="border-t pt-4">
                    <h4 className="font-semibold mb-2">收货地址</h4>
                    <p className="text-sm">
                      {selectedOrderDetail.addressDetail.province} {selectedOrderDetail.addressDetail.city} {selectedOrderDetail.addressDetail.district} {selectedOrderDetail.addressDetail.detailAddress}<br />
                      {selectedOrderDetail.addressDetail.name} - {selectedOrderDetail.addressDetail.phone}
                    </p>
                  </div>
                )}
                <div className="border-t pt-4">
                  <h4 className="font-semibold mb-2">上传文件</h4>
                  <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
                    {selectedOrderDetail.fileList.map((file, index) => (
                      <div key={index} className="block border rounded-lg p-2 text-center">
                        <div className="flex items-center justify-center h-24 bg-gray-100 rounded-md overflow-hidden">
                          {file.url.match(/\.(jpeg|jpg|gif|png)$/i) ? (
                            <img 
                              src={file.url} 
                              alt={file.name} 
                              className="h-full w-full object-contain cursor-pointer hover:scale-105 transition-transform"
                              onClick={() => setImagePreview({ open: true, url: file.url })}
                            />
                          ) : (
                            <a href={file.url} target="_blank" rel="noopener noreferrer" className="flex items-center justify-center h-full w-full">
                              <Package className="h-8 w-8 text-gray-500" />
                            </a>
                          )}
                        </div>
                        <p className="text-xs mt-2 truncate" title={file.name}>
                          {file.url.match(/\.(jpeg|jpg|gif|png)$/i) ? (
                            file.name
                          ) : (
                            <a href={file.url} target="_blank" rel="noopener noreferrer" className="hover:underline">{file.name}</a>
                          )}
                        </p>
                      </div>
                    ))}
                  </div>
                </div>
                {selectedOrderDetail.remark && (
                  <div className="border-t pt-4">
                    <h4 className="font-semibold mb-2">备注</h4>
                    <p className="text-sm">{selectedOrderDetail.remark}</p>
                  </div>
                )}
              </div>
            ) : (
              <p className="text-center py-12 text-gray-500">未找到订单详情。</p>
            )}
          </div>
        </div>
      )}

      {/* Image Preview Modal */}
      {imagePreview.open && (
        <div 
          className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50"
          onClick={() => setImagePreview({ open: false, url: null })}
        >
          <button 
            className="absolute top-4 right-4 text-white text-2xl"
            onClick={() => setImagePreview({ open: false, url: null })}
          >
            &times;
          </button>
          <img 
            src={imagePreview.url || ''} 
            alt="Image Preview" 
            className="max-w-[90vw] max-h-[90vh] object-contain"
            onClick={(e) => e.stopPropagation()}
          />
        </div>
      )}

      {/* 操作对话框 */}
      {operationDialog.open && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-96 max-w-md">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold">
                {operationDialog.type === 'price' && '修改订单金额'}
                {operationDialog.type === 'status' && '修改订单状态'}
                {operationDialog.type === 'courier' && '添加快递信息'}
                {operationDialog.type === 'beian' && '上传备案回执'}
                {operationDialog.type === 'close' && '关闭订单'}
                {operationDialog.type === 'delete' && '删除订单'}
              </h3>
              <Button variant="ghost" size="sm" onClick={closeOperationDialog}>
                <X className="h-4 w-4" />
              </Button>
            </div>

            <div className="space-y-4">
              <div className="text-sm text-gray-600">
                订单号: {operationDialog.order?.orderNo}
              </div>

              {operationDialog.type === 'price' && (
                <div>
                  <label className="block text-sm font-medium mb-2">订单金额 (元)</label>
                  <Input
                    type="number"
                    step="0.01"
                    value={operationForm.price}
                    onChange={(e) => setOperationForm(prev => ({ ...prev, price: e.target.value }))}
                    placeholder="请输入金额"
                  />
                </div>
              )}

              {operationDialog.type === 'status' && (
                <div>
                  <label className="block text-sm font-medium mb-2">订单状态</label>
                  <select
                    value={operationForm.status}
                    onChange={(e) => setOperationForm(prev => ({ ...prev, status: e.target.value }))}
                    className="w-full p-2 border border-gray-300 rounded-md"
                  >
                    <option value="">请选择状态</option>
                    {/* 待处理状态只能修改为处理中 */}
                    {operationDialog.order?.status === STATUS_PENDING && (
                      <option value={STATUS_PROCESSING}>处理中</option>
                    )}
                    {/* 处理中状态只能修改为提交备案 */}
                    {operationDialog.order?.status === STATUS_PROCESSING && (
                      <option value={STATUS_SUBMIT}>提交备案</option>
                    )}
                  </select>
                </div>
              )}

              {operationDialog.type === 'courier' && (
                <div className="space-y-3">
                  <div>
                    <label className="block text-sm font-medium mb-2">快递公司</label>
                    <select
                      value={operationForm.courierCompany}
                      onChange={(e) => setOperationForm(prev => ({ ...prev, courierCompany: e.target.value }))}
                      className="w-full p-2 border border-gray-300 rounded-md"
                    >
                      <option value="">请选择快递公司</option>
                      {Object.entries(COURIER_COMPANIES).map(([value, label]) => (
                        <option key={value} value={value}>{label}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-2">快递单号</label>
                    <Input
                      value={operationForm.courierNo}
                      onChange={(e) => setOperationForm(prev => ({ ...prev, courierNo: e.target.value }))}
                      placeholder="请输入快递单号"
                    />
                  </div>
                </div>
              )}

              {operationDialog.type === 'beian' && (
                <div>
                  <label className="block text-sm font-medium mb-2">备案回执文件</label>
                  <input
                    type="file"
                    accept=".pdf,.jpg,.jpeg,.png"
                    onChange={(e) => setOperationForm(prev => ({ 
                      ...prev, 
                      beianFile: e.target.files?.[0] || null 
                    }))}
                    className="w-full p-2 border border-gray-300 rounded-md"
                  />
                  <div className="text-xs text-gray-500 mt-1">
                    支持 PDF、JPG、PNG 格式文件
                  </div>
                </div>
              )}

              {operationDialog.type === 'close' && (
                <div className="text-sm text-red-600">
                  确认要关闭此订单吗？此操作不可撤销。
                </div>
              )}

              {operationDialog.type === 'delete' && (
                <div className="text-sm text-red-700 bg-red-50 p-3 rounded-md border border-red-200">
                  <div className="flex items-center mb-2">
                    <Trash2 className="h-4 w-4 mr-2" />
                    <span className="font-medium">危险操作警告</span>
                  </div>
                  <p>确认要删除此订单吗？</p>
                  <p className="mt-1 text-xs">此操作将永久删除订单数据，无法恢复！</p>
                </div>
              )}
            </div>

            <div className="flex justify-end space-x-2 mt-6">
              <Button variant="outline" onClick={closeOperationDialog} disabled={operationLoading}>
                取消
              </Button>
              <Button 
                onClick={handleOperation} 
                disabled={operationLoading}
                variant={operationDialog.type === 'delete' ? 'destructive' : 'default'}
              >
                {operationLoading ? (
                  <div className="flex items-center">
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                    处理中...
                  </div>
                ) : (
                  <>
                    {operationDialog.type === 'delete' ? (
                      <Trash2 className="mr-2 h-4 w-4" />
                    ) : (
                      <Save className="mr-2 h-4 w-4" />
                    )}
                    {operationDialog.type === 'delete' ? '确认删除' : '确认'}
                  </>
                )}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 退款确认对话框 */}
      {refundDialog.open && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-96 max-w-md">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-orange-600">
                确认退款
              </h3>
              <Button variant="ghost" size="sm" onClick={closeRefundDialog}>
                <X className="h-4 w-4" />
              </Button>
            </div>

            <div className="space-y-4">
              <div className="text-sm text-gray-600">
                订单号: {refundDialog.order?.orderNo}
              </div>
              
              <div className="text-sm text-red-600 bg-red-50 p-3 rounded-md border border-red-200">
                <div className="flex items-center mb-2">
                  <RefreshCw className="h-4 w-4 mr-2" />
                  <span className="font-medium">退款确认</span>
                </div>
                <p>确认要为此订单申请退款吗？</p>
                <p className="mt-1 text-xs">此操作将向系统提交退款申请。</p>
              </div>
            </div>

            <div className="flex justify-end space-x-2 mt-6">
              <Button variant="outline" onClick={closeRefundDialog} disabled={refundDialog.order ? refundLoading[refundDialog.order.id] || false : false}>
                取消
              </Button>
              <Button 
                onClick={handleRefundConfirm} 
                disabled={refundDialog.order ? refundLoading[refundDialog.order.id] || false : false}
                className="bg-orange-600 hover:bg-orange-700"
              >
                {refundDialog.order && refundLoading[refundDialog.order.id] ? (
                  <>
                    <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                    处理中...
                  </>
                ) : (
                  <>
                    <RefreshCw className="mr-2 h-4 w-4" />
                    确认退款
                  </>
                )}
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

// 订单详情数据类型
interface AddressDetail {
  name: string;
  phone: string;
  province: string;
  city: string;
  district: string;
  detailAddress: string;
}

interface FileInfo {
  name: string;
  url: string;
}

interface OrderDetail {
  id: number;
  addressDetail: AddressDetail;
  orderNo: string;
  status: number;
  statusText: string;
  uploadFileStatus: number;
  totalPrice: number;
  discountAmount: number;
  payPrice: number;
  sealType: string;
  sealMaterialId: string;
  sealClassifyArr: string[];
  reasons: string[];
  province: string;
  city: string;
  district: string;
  phone: string;
  bossPhone: string;
  licenseName: string;
  remark: string;
  createdAt: string;
  createdAtFormat?: string;
  courierNo: string;
  evaluates: any[];
  beian: string;
  fileList: FileInfo[];
}

interface OrderDetailApiResponse {
  code: number;
  msg: string;
  data: OrderDetail;
}

interface ApiResponse {
  code: number;
  msg: string;
  data: {
    list: OrderItem[];
    total: number;
    pageNum: string;
    pageSize: string;
    totalPages: number;
  };
}
